-- Copyright (c) 2024 Huawei Technologies Co., Ltd.
-- openUBMC is licensed under Mulan PSL v2.
-- You can use this software according to the terms and conditions of the Mulan PSL v2.
-- You may obtain a copy of Mulan PSL v2 at:
--         http://license.coscl.org.cn/MulanPSL2
-- THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
-- EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
-- MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
-- See the Mulan PSL v2 for more details.

local class = require 'mc.class'
local imu_communicate = require 'domain.transport.imu_communicate'
local process_channel = require 'domain.bios_firmware.package.channel.firmware_process_channel'
local file_sec = require 'utils.file'
local utils = require 'mc.utils'
local IpmbChannel = class(process_channel)

function IpmbChannel:ctor()
    IpmbChannel.super.ctor(self, 'IpmbChannel')
end

function IpmbChannel:upgrade(ctx, properties)
    if not ctx or not properties or not ctx.BinPath or
        not properties.Offset or not properties.Length or not properties.FirmwareId or
        not properties.Type or not ctx.SystemId then
        error('ipmb channel: invalid param')
    end

    local file_fd, err = file_sec.open_s(ctx.BinPath, 'r')
    if not file_fd then
        error(string.format('ipmb channel: invalid file path, err: %s', err))
    end
    return utils.safe_close_file(file_fd, function()
        file_fd:seek('set', properties.Offset)
        local fimware_data = file_fd:read(properties.Length)
        local firmware_info = {
            RawData = fimware_data,
            FirmwareId = properties.FirmwareId,
            Type = properties.Type
        }
        local imu_cmd = imu_communicate.get_instance()
        imu_cmd:write_firmware(firmware_info, ctx.SystemId)
    end)
end

return IpmbChannel